//
//  RHMQUpgradeListController.m
//  RuiHeAppApp
//
//  Created by Jun on 2023/8/15.
//

#import "RHMQUpgradeListController.h"
#import "SYChartTool.h"
#import "RHMQEndPointModel.h"
#import "RHMQTTManage.h"
#import "RHMQDevModel.h"
#import "RHMQDevRegionModel.h"


@interface RHMQUpgradeListController ()<UITableViewDelegate ,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *dataArray;

@property (nonatomic ,assign) __block NSInteger selectIndex;

@property (nonatomic ,strong) RHMQEndPointModel *curEndPointModel;
@end

@implementation RHMQUpgradeListController


- (NSMutableArray *)dataArray{
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self.navigationItem setTitle:@"选择固件"];
    [self.view setBackgroundColor:CFTabViewBgColor];
    _selectIndex = -1;
    //[self creatData];
    [self setupUI];
    [self getDevRelation];
}

- (void)creatData{
    
    NSDictionary *dict = [SYChartTool readLocalJsonFileWithName:@"MqEndPoint"];
    NSArray *array = [NSArray yy_modelArrayWithClass:[RHMQEndPointModel class] json:dict[@"data"]];
    
    [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        RHMQEndPointModel *model = obj;
        [self.dataArray addObject:obj];
        [model.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            [self.dataArray addObject:obj];
            [obj.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                [self.dataArray addObject:obj];
            }];
        }];
    }];
    
}

- (void)setupUI{
    QMUIButton *addBtn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setFrame:CGRectMake(0, 0,40, 64)];
    [addBtn setBackgroundColor:UIColor.clearColor];
    [addBtn setTitleColor:CFMainColor forState:UIControlStateNormal];
    [addBtn.titleLabel setFont:[UIFont systemFontOfSize:16]];
    [addBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [addBtn setTitle:@"上传最新版本" forState:UIControlStateNormal];
    UIBarButtonItem *rightBarBtn = [[UIBarButtonItem alloc] initWithCustomView:addBtn];
    self.navigationItem.rightBarButtonItem = rightBarBtn;
    kWeakSelf;
    [[addBtn rac_signalForControlEvents:UIControlEventTouchUpInside] subscribeNext:^(__kindof UIControl * _Nullable x) {
        [weakSelf uploadDeviceVersion];
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    [self.view addSubview:_tableView];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.insets(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [_tableView addHeaderRefresh:^{
        [weakSelf getDevRelation];
    }];
}


#pragma mark - Network
//获取端点关系
- (void)getDevRelation{
    //@"updateDtoList": @[@{@"sn":self.curEndPointModel.sn,
//    @"firmwareTypes":@"EMS"
//  }]
    [self.dataArray removeAllObjects];
    NSDictionary *para = @{@"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,
                           @"password":[RHMQTTManage shareMQTTManage].devModel.secretKey
                           
                           
    };
   
    [RHMQDevRegionModel startGetWithCompletionAPIKey:D_getDevRelation argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
            if(resultModel.data){
      
                [[(RHMQDevRegionModel *)resultModel.data data] enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    RHMQEndPointModel *model = obj;
                    [self.dataArray addObject:obj];
                    [model.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        [self.dataArray addObject:obj];
                        [obj.nodes enumerateObjectsUsingBlock:^(RHMQEndPointModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                            [self.dataArray addObject:obj];
                        }];
                    }];
                }];
                
                
                [self.tableView reloadData];
            }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            [self.tableView endHeaderRefresh];
    }];
}


#pragma mark ------- 上传固件版本 ------
-(void)uploadDeviceVersion
{
    if(!self.curEndPointModel){
        [QMUITips showError:@"请选择一个端点"];
        return;
    }
        
    QMUIAlertController *alertController = [QMUIAlertController alertControllerWithTitle:@"请输入最新版本号" message:@"" preferredStyle:QMUIAlertControllerStyleAlert];
    [alertController addAction:[QMUIAlertAction actionWithTitle:@"确定" style:QMUIAlertActionStyleDestructive handler:^(__kindof QMUIAlertController * _Nonnull aAlertController, QMUIAlertAction * _Nonnull action) {
        QMUITextField *textField = [aAlertController.textFields firstObject];
        NSDictionary *para = @{@"deviceId":[RHMQTTManage shareMQTTManage].devModel.devId,
                               @"firmwareType":self.curEndPointModel.firmwareType,
                               @"lastVersion":textField.text,
                               @"password":[RHMQTTManage shareMQTTManage].devModel.secretKey,
                               @"sn":self.curEndPointModel.sn
        };
        
        [BaseModel startWithCompletionAPIKey:D_uploadVersion argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            if(resultModel.code == 200){
                [QMUITips showSucceed:@"上传成功"];
            }
            
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];
    }]];
    [alertController addCancelAction];
    [alertController addTextFieldWithConfigurationHandler:^(QMUITextField * _Nonnull textField) {
        textField.placeholder = @"请输入版本号";
    }];
    
    [alertController addTextFieldWithConfigurationHandler:^(QMUITextField * _Nonnull textField) {
        textField.placeholder = @"请输入描述";
    }];
   
    // 输入框的布局默认是贴在一起的，默认不需要修改，这里只是展示可以通过这个 block 自行调整。
    alertController.alertTextFieldMarginBlock = ^UIEdgeInsets(__kindof QMUIAlertController * _Nonnull aAlertController, NSInteger aTextFieldIndex) {
        UIEdgeInsets margin = UIEdgeInsetsZero;
        if (aTextFieldIndex == aAlertController.textFields.count - 1) {
            margin = UIEdgeInsetsSetBottom(margin, 16);
        } else {
            margin = UIEdgeInsetsSetBottom(margin, 4);
        }
        return margin;
    };
    
    [alertController showWithAnimated:YES];
    
    
    
    
}

#pragma mark - UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 70;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 15)];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 15;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 30.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 30)];
    return footView;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleGray];
    [cell.textLabel setFont:[UIFont systemFontOfSize:14]];
    [cell.textLabel setNumberOfLines:3];
    [cell.textLabel setTextColor:indexPath.row == _selectIndex?CFMainColor:kCOLOR_HEX(@"666666")];
    
    QMUIButton *btn = [QMUIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:indexPath.row == _selectIndex?[UIImage imageNamed:@"submit_success"]:nil forState:UIControlStateNormal];
    [btn setTitleColor:kCOLOR_HEX(@"666666") forState:UIControlStateNormal];
    [btn.titleLabel setFont:[UIFont systemFontOfSize:13]];
    [btn setImagePosition:QMUIButtonImagePositionRight];
    [btn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
    [btn setFrame:CGRectMake(0, 0, 23, 15)];
    [cell setAccessoryView:btn];
    
    RHMQEndPointModel *model = self.dataArray[indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@-%@\n类型：%@\n版本：%@",model.type,model.sn,StrValid(model.firmwareType)?model.firmwareType:@"--",model.lastVersion]];
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    self.curEndPointModel = self.dataArray[indexPath.row];
}



@end
